package com.example.springdemo.interceptor;

import com.example.springdemo.domain.base.BaseRes;
import com.example.springdemo.service.impl.RedisService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * AuthInterceptor
 *
 * @author wenguang
 * @date 2020/11/26 10:21
 */
public class AuthInterceptor implements HandlerInterceptor {

    @Value("${custom.debug}")
    private boolean isDebug;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        if (isDebug) {
            return true;
        }

        String rootToken = request.getHeader("authorization");
        if (Objects.nonNull(rootToken)) {
            redisService.expireKey(rootToken, (long) (60 * 60 * 2));
            return true;
        } else {
            PrintWriter writer = response.getWriter();
            writer.write(objectMapper.writeValueAsString(
                new BaseRes<>(HttpStatus.UNAUTHORIZED.value(), "请登录后重试.", request.getRequestURL())));
            writer.flush();
            writer.close();
            return false;
        }
    }
}
